package org.geektimes.projects.autoconfiguration;

import org.apache.ibatis.io.VFS;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: jipeng
 * @Description:
 * @Date: Created in 2021/5/26 8:30
 */
public class SpringBootVFS extends VFS {
    private final ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(this.getClass().getClassLoader());

    public SpringBootVFS() {
    }

    @Override
    public boolean isValid() {
        return true;
    }

    @Override
    protected List<String> list(URL url, String path) throws IOException {
        String urlString = url.toString();
        String baseUrlString = urlString.endsWith("/") ? urlString : urlString.concat("/");
        Resource[] resources = this.resourceResolver.getResources(baseUrlString + "**/*.class");
        return (List) Stream.of(resources).map((resource) -> {
            return preserveSubpackageName(baseUrlString, resource, path);
        }).collect(Collectors.toList());
    }

    private static String preserveSubpackageName(String baseUrlString, Resource resource, String rootPath) {
        try {
            return rootPath + (rootPath.endsWith("/") ? "" : "/") + resource.getURL().toString().substring(baseUrlString.length());
        } catch (IOException var4) {
            throw new UncheckedIOException(var4);
        }
    }
}
